package com.miyu.common.utils.filter.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.miyu.common.utils.filter.result.ComResult;
import io.lettuce.core.RedisConnectionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {

    /**
     * 全局异常拦截（拦截项目中的NotLoginException异常）
     * token异常时错误问题
     * @param nle
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public Object handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
            {
        /* 打印堆栈，以供调试*/
        nle.printStackTrace();
        /* 判断场景值，定制化异常信息*/
        String message = "";
        if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "NOT_TOKEN";
        }
        else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "INVALID_TOKEN";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "TOKEN_TIMEOUT";
        }
        else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "BE_REPLACED";
        }
        else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "KICK_OUT";
        }
        else {
            message = "NOT_TOKEN";
        }
        return ComResult.error(message);
    }
    @ExceptionHandler(value = RedisConnectionFailureException.class)
    public Object RedisConnectionFailureException(HttpServletRequest request, Exception e,HttpServletResponse response){
        System.out.println("redis："+e.getMessage());
        log.error("redis连接异常");
        return   response;
    }

    @ExceptionHandler(value = Exception.class)
    public Object handlerGlobeException(HttpServletRequest request, Exception e){
        System.out.println("全局异常拦截："+e.getMessage());
      return   ComResult.error("ERROR");
    }



}
